// src/api/service/UserService.tsx
import graphqlClient from '../../api/GraphqlConfig';
import { GET_USERS, UPDATE_USER_STATUS } from '../gql/UserGQL';

// 定义数据类型
export interface Role {
    id: string;
    name: string;
    roleId: string;
    userId: string;
    createTime: string;
    updateTime: string;
}

export interface Authority {
    id: string;
    name: string;
    authorityId: string;
    userId: string;
    createTime: string;
    updateTime: string;
}

export interface User {
    id: string;
    username: string;
    nickname: string;
    status: string;
    avatarAddr: string;
    createTime: string;
    updateTime: string;
    roles: Role[];
    authorities: Authority[];
}

export interface UsersResponse {
    users: User[];
}

class UserService {
    /**
     * 获取用户列表
     * @returns 用户列表
     */
    async getUsers(): Promise<User[]> {
        try {
            const result = await graphqlClient.query<{ user: UsersResponse }>({
                query: GET_USERS
            });
            return result.data!.user.users;
        } catch (error) {
            console.error('获取用户列表失败:', error);
            throw error;
        }
    }

    /**
     * 更新用户状态
     * @param userId 用户ID
     * @param status 新状态
     * @returns 更新结果
     */
    async updateUserStatus(userId: string, status: string): Promise<boolean> {
        try {
            const result = await graphqlClient.mutate<{ user: { updateUserStatus: boolean } }>({
                mutation: UPDATE_USER_STATUS,
                variables: {
                    userId,
                    status
                }
            });
            return result.data!.user.updateUserStatus;
        } catch (error) {
            console.error('更新用户状态失败:', error);
            throw error;
        }
    }
}

// 创建并导出 UserService 实例
export const userService = new UserService();
